﻿using CommonTools;
using Newtonsoft.Json;
using shop.Bll;
using shop.Bll.cost;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace shop.cost
{
    public partial class PostPriceEditor : Form, IEditItemDialog<PostPriceDto>
    {
        public PostPriceDto Item { set; get; }
        PostPriceBll _bll = new PostPriceBll();

        IEnumerable<string> _provs= null;


        public PostPriceEditor()
        {
            InitializeComponent();


            cl_specPrice.ValueType= typeof(decimal);
            cl_specWeight.ValueType= typeof(decimal);
            cl2_UnitWeight.ValueType= typeof(decimal);
            cl2_Price.ValueType= typeof(decimal);
            cl2_WeightRange.ValueType= typeof(decimal);
            box_BeginDate.Value = null;
            box_EndDate.Value= null;

            box_calcMethod.LazyInitItemsAsync<PostCalcStrategy>(async () => await new PostCalcStrategyBll().Query(null),
                nameof(PostCalcStrategy.Name), new[] { nameof(PostCalcStrategy.Name) });
        }

        private async void btnOk_Click(object sender, EventArgs e)
        {
            if(Item == null)
            {
                Item = new PostPriceDto();
            }

            Item.BeginDate = box_BeginDate.Value;
            Item.EndDate = box_EndDate.Value;
            Item.logistics_name = box_logistics_name.Text.Trim();
            Item.provinceJson = box_provinceJson.Text.Trim();
            Item.MinAmount = box_minAmount.Value;
            Item.weightRatio = box_weightRatio.Value;
            Item.FUser = UserBll.CurrentUser.Name;

            var specList = new List<SpecialRange>();
            foreach (DataGridViewRow row in gridSpec.Rows)
            {
                if (row.IsNewRow)
                    break;

                var spe = new SpecialRange()
                {
                    WeightRange = row.Cells[cl_specWeight.Index].Value.IsNull(0m),
                    Price = row.Cells[cl_specPrice.Index].Value.IsNull(0m),
                    UnitWeight = 0,
                };
                specList.Add(spe);
            }

            var common = new List<SpecialRange>();
            foreach (DataGridViewRow row in grid2.Rows)
            {
                if (row.IsNewRow)
                    break;

                var com = new SpecialRange()
                {
                    WeightRange = row.Cells[cl2_WeightRange.Index].Value.IsNull(0m),
                    Price = row.Cells[cl2_Price.Index].Value.IsNull(0m),
                    UnitWeight = row.Cells[cl2_UnitWeight.Index].Value.IsNull(0m),
                };

                common.Add(com);
            }

            //省份
            var sb = new StringBuilder();
            foreach (DataGridViewRow row in grid_prov.Rows)
            {
                if (row.IsNewRow)
                    break;
                if (row.Cells[cl_selected.Index].Value.IsNull(true) == true)
                {
                    sb.Append((row.Cells[cl_prov.Index].Value?.ToString() ?? string.Empty).Replace("省","").Replace("市",""));
                    sb.Append(",");
                }
            }
            Item.provinceJson = sb.ToString().Trim(',');

            //仓库
            sb = new StringBuilder();
            foreach (DataGridViewRow row in grid_stock.Rows)
            {
                if (row.IsNewRow)
                    break;

                sb.Append(row.Cells[cl_ck.Index].Value?.ToString()?.Trim());
                sb.Append(",");
            }
            Item.StockJson = sb.ToString().Trim(',');


            Item.SpecialRangeJson= JsonConvert.SerializeObject(specList);
            Item.CommonRangeJson= JsonConvert.SerializeObject(common);

            Item.roundMode = "向上取整";

            if(Item.BeginDate == null)
            {
                MessageBox.Show("起始日期不能为空!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            if (Item.EndDate == null) Item.EndDate = new DateTime(2099, 1, 1);

            if(string.IsNullOrEmpty(Item.logistics_name))
            {
                MessageBox.Show("快递功能不能为空!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Result res = await _bll.SaveItem(Item);

            if (res.ErrorCode != ResultCode.Ok)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private  void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void btn_delete_Click(object sender, EventArgs e)
        {
            if (Item == null || Item.Id <= 0)
            {
                MessageBox.Show("不能执行此操作", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var res = await _bll.DeleteItem(Item.Id);

            if (res.ErrorCode != ResultCode.Ok)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private async void PostPriceEditor_Load(object sender, EventArgs e)
        {
            _provs = new[]
            {
                "贵州",
                "湖南",
                "辽宁",
                "宁夏回族自治区",
                "陕西",
                "甘肃",
                "广西壮族自治区",
                "河南",
                "湖北",
                "北京",
                "福建",
                "江西",
                "内蒙古自治区",
                "上海",
                "新疆维吾尔自治区",
                "云南",
                "山东",
                "安徽",
                "广东",
                "河北",
                "黑龙江",
                "吉林",
                "山西",
                "四川",
                "天津",
                "浙江",
                "海南",
                "江苏",
                "青海",
                "重庆",
                "西藏自治区",
            };

            this.grid_prov.AddItems(_provs, a => false, a => a);


            if (Item != null)
            {
                if (Item.Id > 0)
                {
                    Item = await _bll.GetItem(Item.Id);
                }

                box_BeginDate.Value = Item.BeginDate;
                box_EndDate.Value = Item.EndDate;
                box_logistics_name.Text = Item.logistics_name;
                box_provinceJson.Text = Item.provinceJson;
                box_minAmount.Value = Item.MinAmount;
                box_weightRatio.Value = Item.weightRatio;
                box_FUser.Text = Item.FUser;

                foreach (DataGridViewRow row in grid_prov.Rows)
                {
                    var prov = row.Cells[cl_prov.Index].Value?.ToString().Replace("省", "").Replace("市", "");
                    if (string.IsNullOrEmpty(prov) == false && Item.provinceJson?.Contains(prov) == true)
                    {
                        row.Cells[cl_selected.Index].Value = true;
                    }
                }

                var stocks = Item.StockJson?.Split(',');
                if (stocks != null && stocks.Length != 0)
                {
                    grid_stock.AddItems(stocks, a => a);
                }

                //特殊区间
                gridSpec.AddItems(Item.SpceialRangeList,
                    a => a.WeightRange.ToString("#,0.###"),
                    a => a.Price.ToString("#,0.###")
                    );
                //续费区间
                grid2.AddItems(Item.CommonRangeList,
                    a => a.WeightRange.ToString("#,0.###"),
                    a => a.UnitWeight.ToString("#,0.###"),
                    a => a.Price.ToString("#,0.###")
                    );
                
            }
            else
            {
                //box_enable.Checked = true;
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            var items = new List<string>();

            foreach (DataGridViewRow row in grid_prov.Rows)
            {
                if (row.Cells[cl_selected.Index].Value.IsNull(false) == true)
                {
                    items.Add(row.Cells[cl_prov.Index].Value?.ToString());
                }
            }

            if (checkBox1.Checked)
            {
                // 只显示选中内容
                grid_prov.Rows.Clear();
                grid_prov.AddItems(items, a => true, a => a);
            }
            else
            {
                grid_prov.Rows.Clear();
                grid_prov.AddItems(_provs, a => false, a => a);

                foreach (DataGridViewRow row in grid_prov.Rows)
                {
                    var item = row.Cells[cl_prov.Index].Value?.ToString();
                    if (string.IsNullOrEmpty(item) == false && items.Contains(item))
                    {
                        row.Cells[cl_selected.Index].Value = true;
                    }
                }
            }
        }

        private void box_findLogi_RequestValidate(CommonTools.Controls.GuanTextBox arg1, CommonTools.Controls.FastValueArgs arg2)
        {

        }
    }
}
